package cn.com.netedge.iot.frontend.comm.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.enums.OnlineStatusEnum;
import cn.com.netedge.iot.common.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class FeCommCacheUtil {
    private static final Logger logger = LoggerFactory.getLogger(FeCommCacheUtil.class);
    private static final short NOTIFY_TYPE_RTU_ONOFFLINE = 4;

    public static void setString(String key, String value) {
        RedisUtil.setPermanently(key, value);
        addFilterKey(key, value);
    }

    public static void setString(String key, String value, int timeout) {
        RedisUtil.set(key, value, timeout, TimeUnit.SECONDS);
        addFilterKey(key, value);
    }

    private static void addFilterKey(String key, String value) {
        if(key.indexOf(CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE) >=0) {
            RedisUtil.hset(CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE + "device_map", key, "");
        } else if(key.indexOf(CacheKeyConstants.KEY_DEVICE_RUNNING) >=0) {
            JSONObject temp = JSON.parseObject(value);
            if(OnlineStatusEnum.OFFLINE.getCode() == temp.getIntValue("curStatus")) {
                RedisUtil.hdel(CacheKeyConstants.KEY_DEVICE_RUNNING + "map", key);
                logger.debug("hdel {} , key:{} ", CacheKeyConstants.KEY_DEVICE_RUNNING + "map", key);
            } else {
                RedisUtil.hset(CacheKeyConstants.KEY_DEVICE_RUNNING + "map", key, "");
                logger.debug("hset {} , key:{} , value:{}", CacheKeyConstants.KEY_DEVICE_RUNNING + "map", key, value);
            }
        }
    }

    public static void delKey(String key) {
        RedisUtil.delete(key);
        delFilterKey(key);
    }

    public static void delFilterKey(String key) {
        if(key.indexOf(CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE) >=0) {
            RedisUtil.hdel(CacheKeyConstants.KEY_FRONTEND_COMM_MACHINE + "device_map", key);
        }
    }

    public static Set<String> keys(String key) {
        return RedisUtil.hkeys(key + "map");
    }
}
